<?php
class Captcha
{
    public static function make()
    {
        $response = new Response(null, 200, array('Content-Type' => 'image/gif'));
        $configs = Config::get('captcha');
        $str = Str::lower(Str::random($configs['length']));

        Session::put($configs['session'], Hash::make($str));

        $image = imagecreatetruecolor($configs['width'], $configs['height']);

        $bgColor = imagecolorallocate($image, $configs['background']['r'], $configs['background']['g'], $configs['background']['b']);
        $textColor = imagecolorallocate($image, rand(70, 190), rand(70, 190), rand(70, 190));

        imagefilledrectangle($image, 0, 0, $configs['width'] - 1, $configs['height'] - 1, $bgColor);

        $font = __DIR__ . DS . 'jenifer.ttf';

        $fontSize = $configs['height'] / 1.6;
        $angle = rand (-10, 10);
        $box = imagettfbbox($fontSize, $angle, $font, $str);
        $x = (int)($configs['width'] - $box[4]) / 2;
        $y = (int)($configs['height'] - $box[5]) / 2;
        imagettftext($image, $fontSize, $angle, $x, $y, $textColor, $font, $str);
        imagegif($image);

        imagedestroy($image);
        return $response;
    }

    public static function check($text)
    {
        return Hash::check($text, Session::get(Config::get('captcha.session')));
    }
}